<?php

class UserController extends ModuleController {

    private $profile_links = array(array('link'=>'profile','text'=>'Просмотр'),
                                   array('link'=>'profile/edit','text'=>'Редактировать'));
    private $email, $password, $reg_data;
    
    //----LISTENERS---//
    public function onCreatePage() {
        $this->form_manager->addHandler($this);
        $this->model = new LRModel();
    }
    //----PAGES----//
    public function uploadavatar_ajax() {
        $valid_formats = array("jpg", "png", "gif", "jpeg"); // допустимые форматы
        if (isset($_FILES['file']['name'])) {
            $name = $_FILES['file']['name'];
            $size = $_FILES['file']['size'];
            $error = $_FILES['file']['error']; 
            if ($error)
            {
                echo "Ошибка загрузки";
                exit();
            }
            list($txt, $ext) = explode(".", $name);
            if (!in_array(strtolower($ext), $valid_formats))
            {
                echo "Допустимые форматы: jpg|jpeg|png|gif)";
                exit();
            }
            if ($size > 1024*1024)
            {
                echo "Максимальный размер файла не должен превышать 1MB";
                exit();
            }
            $tmp = $_FILES['file']['tmp_name'];
            if ($this->user->uploadAvatar($tmp)) {
                echo "<img src=\"" . url($this->user->photo_big) . "\" class=\"preview\"> "; // показываем превьюшку
            } else {
                echo "Ошибка загрузки";
            }
        }
        exit();
    }
    public function editprofile_arguments_checker() {
            $current_args = $this->getArgs();
            //2 - user num
            if (isset($current_args[2]) && $current_args[2] >= 0) {
            if ($this->user[$current_args[2]] === false) {
                return FAIL;
            }
        }
        return OK;
    }
    /**
     * @blocks: navigation, loginblock
     */
    public function editprofile() {
        $current_args = $this->getArgs();
        if (isset($current_args[2])) {
            if ($this->user->is_admin || $current_args[2] == $this->user->user_id)
            {
                $user = $this->user[$current_args[2]];
            }
            else
            {
                $user = $this->user;
            }
        } else {
            $user = $this->user;
        }

        //TABBAR
        $this->profile_links[1]['active'] = true;
        $this->output($this->view->gettabs(array('links' => $this->profile_links)));

        //MAIN CONTENT
        $input_file_html = $this->view->getuser_avatar_inputbox();
        $form_params = array(
            'body' => $input_file_html,
            'action' => 'uploadavatar',
            'id' => 'formUpload',
            'multipart' => true,
            'form_action'=>url('uploadavatar'),
            'name'=>'uploadavatar'
        );
        $uploadavatar_form_html = View::form_ex($form_params);

        $date = getdate();
        $params['user'] = $user;
        $params['current_year'] = $date['year']-1;
        $params['countries'] = Countries_Helper::getCountries();
        $form_data = $this->getFormManager()->loadPOSTData('editprofile');
        if(empty($form_data)){
            $form_data['user_nickname'] = $this->user->user_nickname;
            $form_data['user_email'] = $this->user->user_email;    
            if(!empty($this->user->bdate))
            {
                $date = date_parse($this->user->bdate);
                $form_data['bdate_day'] = $date['day'];
                $form_data['bdate_mounth'] = $date['month'];
                $form_data['bdate_year'] = $date['year'];
            }
            $form_data['country'] = strtoupper($this->user->country);
            if(!empty($this->user->city)) $form_data['city'] = $this->user->city;
            if(!empty($this->user->sex)) $form_data['sex'] = $this->user->sex;
            if(!empty($this->user->wmid)) $form_data['wmid'] = $this->user->wmid;
            if(!empty($this->user->wm_pouch)) $form_data['wm_pouch'] = $this->user->wm_pouch;
            if(!empty($this->user->get_newtasks)) $form_data['get_newtasks'] = $this->user->get_newtasks;
            if(!empty($this->user->get_notifies)) $form_data['get_notifies'] = $this->user->get_notifies;
        }
        $params['data'] = $form_data;
        $params['errors'] = $this->getFormManager()->getErrorsForFields('editprofile');
        $base_form_params = array(
            'body' => $this->view->getuser_editprofile($params),
            'action' => 'editprofile',
            'buttons'=>'<input type="submit" name="submit_editform" value="Обновить профиль">',
            'name'=>'editprofile'
        );
        
        $base_form_html = View::form_ex($base_form_params);
        $this->output($uploadavatar_form_html.$base_form_html);
        return OK;
    }
    public function showprofile_arguments_checker() {
        $current_args = $this->getArgs();
        //2 - user num
        if (isset($current_args[2]) && $current_args[2] >= 0) {
            if ($this->user[$current_args[2]] === false) {
                return FAIL;
            }
        }
        return OK;
    }
    /**
     * @blocks: navigation, loginblock
     */
    public function showprofile() {
        $current_args = $this->getArgs();
        if (isset($current_args[2])) {
            if ($this->user->is_admin || $current_args[2] == $this->user->user_id)
            {
                $user = $this->user[$current_args[2]];
            }
            else
            {
                $user = $this->user;
            }
        } else {
            $user = $this->user;
        }

        $is_owner = false;
        if ($this->user->isLogged && $user->user_id == $this->user->user_id)
            $is_owner = true;

        $this->profile_links[0]['active'] = true;

        if (!$is_owner)
            $this->profile_links[0]['link'] = 'profile/' . $user->user_id;
        if (!$is_owner && !$this->user->is_admin)
            unset($this->profile_links[1]);
        if ($this->user->is_admin && !$is_owner)
            $this->profile_links[1]['link'] = 'profile/edit/' . $user->user_id;
        $this->output($this->view->gettabs(array('links' => $this->profile_links)));

        //VK DATA
        $vk_model = new VKModel();
        $vk_data = $vk_model->getVKAccountByUserId($user->user_id);
        $vk_html = "";
        $params['vk']['is_attached'] = false;
        if ($vk_data !== FALSE) {
            $params['vk']['is_attached'] = true;
            $vk_html = $this->view->getvk_statistic_table(array('data' => $vk_data));
        }
        $params['vk']['html'] = $vk_html;
        $params['user'] = $user;
        $this->output($this->view->getuser_profile($params));
        return OK;
    } 
    public function registration_arguments_checker() {
        if($this->user->isLogged)
            return $this->registry->router->getAction('');
        
        return FAIL;
    }
    /**
     * @blocks: navigation, loginblock
     */
    public function registration() { 
        $params['data'] = $this->getFormManager()->loadPOSTData('registration');
        $params['errors'] = $this->getFormManager()->getErrorsForFields('registration');
        $form_params = array(
            'body' => $this->view->getuser_registration_form($params),
            'action' => 'registration',
            'buttons'=>'<input type="submit" value="Зарегистрироваться">'
        );
        $registration_form_html = View::form_ex($form_params);
        
        $this->output($registration_form_html);
        return OK;
    }
    public function logout() {
        if(empty($_POST['action']))
        {
            $user = $this->user;
            $user->doLogout();
            Event::fireEvent('message', array('message'=>"Вы вышли из системы"));
        }
        redirect(DIR_BASE);
        return $this->router->getAction('');
    }
    public function dettachVKAccount_arguments_checker(){
        if(!$this->user->isLogged) return VALIDATION_FAILED;  
        return  VALIDATION_ACCEPTED;
    }
    public function dettachVKAccount() {
        $vkmodel = new VKModel();
        
        if($vkmodel->hasVKAccountInBaseByUserId($this->user->user_id))
        {
           if($vkmodel->removeVKAccountByUserId($this->user->user_id))
           {
               Event::fireEvent("message", array('message' => 'Аккаунт отключен'));
           }
           else
           {
               Event::fireEvent("message", array('message' => 'Ошибка отключения'));
           }
        }
        else
            return NOT_FOUND;
        redirect($_SERVER['HTTP_REFERER']);
        return $this->router->getAction('profile');
    }
    public function attachVKAccount_arguments_checker(){
        if(!isset($_GET['code'])) return FAIL;
        if(!$this->user->isLogged) return FAIL;  
        return  VALIDATION_ACCEPTED;
    }
    public function attachVKAccount() {
        $code = $_GET['code'];
        $next_action = $this->router->getAction('profile');
        
        $this->load->library('class.Helper_VK.php', 'user');
        $this->load->library('class.vkapi.php', 'user');
        $vkmodel = new VKModel();
        
        if($vkmodel->hasVKAccountInBaseByUserId($this->user->user_id))
        {
            Event::fireEvent("message", array('message' => 'Аккаунт был прикреплен ранее'));
            redirect_back();
            return $next_action;
        }
        $VK = new vkapi(VK_APP_ID, VK_APP_PASSWORD, 'http://localhost/pleasure/profile/attach/vk/');
        $answer = $VK->getToken($code);
        
        if($answer === FALSE)
            return false;
        if (isset($answer['error']))
            return false;
        
        if($vkmodel->hasVKAccountInBase($answer['user_id']))
        {
            Event::fireEvent("message", array('message' => 'Этот ВК уккаунт уже используется другим пользователем'));
            redirect_back();
            return $next_action; 
        }
        
        //получаем токен для вызова АПИ функций
        $data = HelperVK::getVKMainData($VK, $answer['access_token']);
        //обновляем данные об ВК аккаунте при каждом логине
        if($vkmodel->updateVKAccount(array('user_id'=>$this->user->user_id,'vk_id'=>$answer['user_id'], 'num_of_friends'=>$data['num_of_friends'], 'sex'=>$data['sex'], 'bdate'=>$data['bdate'])))
            Event::fireEvent("message", array('message' => 'Аккаунт прикреплен'));
        else
            Event::fireEvent("message", array('message' => 'Ошибка прикрепления аккаунта'));
        redirect($_SERVER['HTTP_REFERER']);
        return $next_action;  
    }
    public function refreshvkdata_arguments_checker(){
        if(!isset($_GET['code'])) return VALIDATION_FAILED;
        if(!$this->user->isLogged) return VALIDATION_FAILED;  
        return  VALIDATION_ACCEPTED;
    }
    public function refreshvkdata() {
        $code = $_GET['code'];
        $next_action = $this->router->getAction('profile');
        
        $vkmodel = new VKModel();
        $this->load->library('class.vkapi.php', 'user');
        $this->load->library('class.Helper_VK.php', 'user');
        
         if(!$vkmodel->hasVKAccountInBaseByUserId($this->user->user_id)) return NOT_FOUND; 
        
        $VK = new vkapi(VK_APP_ID, VK_APP_PASSWORD, $code, 'http://localhost/pleasure/profile/refresh/vk/');
        $answer = $VK->getToken();
        if($answer === FALSE || isset($answer['error'])){ 
            Event::fireEvent("message", array('message' => 'Ошибка обновления данных'));
            redirect($_SERVER['HTTP_REFERER']);
            return $next_action;
        }
        //получаем токен для вызова АПИ функций
        $data = HelperVK::getVKMainData($VK, $answer['access_token']);
        
        if($vkmodel->updateVKAccount(array('user_id'=>$this->user->user_id, 'vk_id'=>$answer['user_id'], 'num_of_friends'=>$data['num_of_friends'], 'sex'=>$data['sex'], 'bdate'=>$data['bdate'])))
        {
            Event::fireEvent("message", array('message' => 'Данные обновлены'));
        }
        else 
        {
            Event::fireEvent("message", array('message' => 'Ошибка обновления данных'));
        }
        redirect($_SERVER['HTTP_REFERER']);
        return $next_action;
    }  
    public function vklogin_arguments_checker(){
        if($this->user->isLogged) return $this->router->getAction('');
        return OK;
    }
    public function vklogin() {
        $user = $this->user;

        if(isset($_GET['code'])) 
            $code = $_GET['code'];
        else
            return NOT_FOUND;
        
        $params = array('strategy'=>'VK', 'code'=>$code);     
        if(isset($this->email)) $params['email'] = $this->email;
        if(isset($this->password)) $params['password'] = $this->password;
        if(isset($this->reg_data)) $params['reg_data'] = $this->reg_data;
        $result = $user->doLogin($params);

        if ($result === VKLoginStrategy::SHOW_EMAIL_FORM) {
            $params['data'] = $this->getFormManager()->loadPOSTData('registration');
            $params['errors'] = $this->getFormManager()->getErrorsForFields('attachemail');
            $base_form_params = array(
                'body' => $this->view->getuser_email_form($params),
                'action' => 'attachemail',
                'buttons' => '<input type="submit" value="Далее">',
            );
            $base_form_html = View::form_ex($base_form_params);
            $this->output("Для продолжения регистрации укажите Ваш e-mail:");
            $this->output($base_form_html);
        }
        elseif($result === VKLoginStrategy::SHOW_PASSWORD_FORM)
        {
            $params['errors'] = $this->getFormManager()->getErrorsForFields('attachpassword');
            $base_form_params = array(
                'body' => $this->view->getuser_password_form($params),
                'action' => 'attachpassword',
                'buttons' => '<input type="submit" value="Далее">',
                'hidden_fields' => array('email'=>$this->email)
            );
            $base_form_html = View::form_ex($base_form_params);
            $this->output("Для прикрепления аккаунта к указанному e-mail введите пароль:");
            $this->output($base_form_html);
            return OK;
        }
        elseif($result === VKLoginStrategy::SHOW_REG_FORM)
        {
            $params['data'] = $this->getFormManager()->loadPOSTData('registration');
            $params['errors'] = $this->getFormManager()->getErrorsForFields('sn_register_form');
            $base_form_params = array(
                'body' => $this->view->getuser_sn_register_form($params),
                'action' => 'sn_register_form',
                'buttons' => '<input type="submit" value="Создать профиль">',
                'hidden_fields' => array('email'=>$this->email)
            );
            $base_form_html = View::form_ex($base_form_params);
            $this->output("Для создания аккаунта неообходимо заполнить следующие поля:");
            $this->output($base_form_html);  
            return OK;
        }
        elseif($result === false)
        {
             Event::fireEvent("message", array('message' => 'Ошибка входа!'));
             return $this->router->getAction('');
        }
        else
        {
             Event::fireEvent("message", array('message' => 'Вход успешен!'));
             return $this->router->getAction('');
        }
    }  
    //----HANDLERS----//
    public function validate_post_editprofile(&$data, &$scope, &$manager) {
        $iserror = false;
        //NICKNAME
        if (empty($data['user_nickname'])) {
            $iserror = true;
            $manager->addErorrMessageForField("user_nickname", "Укажите никнейм");
        } elseif (strlen($data['user_nickname']) < 3) {
            $iserror = true;
            $manager->addErorrMessageForField("nickname", "Слишком короткий никнейм");
        } elseif (strlen($data['user_nickname']) > 64) {
            $iserror = true;
            $manager->addErorrMessageForField("user_nickname", "Слишком длинный никнейм");
        } elseif (!preg_match("/^[a-zа-я0-9]{3,64}+$/ui", $data['user_nickname'])) {
            $iserror = true;
            $manager->addErorrMessageForField("user_nickname", "Введены недопустимые символы");
        } elseif ($this->user->user_nickname != $data['user_nickname'] && $this->user->model->hasUserInBaseByNickname($data['user_nickname'])) {
            $iserror = true;
            $manager->addErorrMessageForField("user_nickname", "Такой нинейм уже используется в системе");
        }
        //E-MAIL /^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$/
        if (empty($data['user_email'])) {
            $iserror = true;
            $manager->addErorrMessageForField("user_email", "Укажите e-mail");
        } elseif (!preg_match("/^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$/ui", $data['user_email'])) {
            $iserror = true;
            $manager->addErorrMessageForField("user_email", "Не допустимый формат e-mail");
        } elseif ($this->user->user_email != $data['user_email'] && $this->user->model->hasUserInBaseByEmail($data['user_email'])) {
            $iserror = true;
            $manager->addErorrMessageForField("user_email", "Такой e-mail уже используется в системе");
        }   
        //BDATE
        if(!empty($data['bdate_day']) && !empty($data['bdate_mounth']) && !empty($data['bdate_year'])
           && $data['bdate_day'] != 0 && $data['bdate_mounth'] !=0 && $data['bdate_year'] !=0)
        {
            $cur_date = getdate();
            $cur_year = $cur_date['year'];
            if(!is_numeric($data['bdate_day']) || !is_numeric($data['bdate_mounth']) || !is_numeric($data['bdate_year']))
            {
                $iserror = true;
                $manager->addErorrMessageForField("bdate", "Не правильный формат даты"); 
            }
            elseif(($data['bdate_day'] < 1 || $data['bdate_day'] > 31)
                || ($data['bdate_mounth'] < 1 || $data['bdate_mounth'] > 12)
                || ($data['bdate_year'] > ($cur_year-1) || $data['bdate_year'] < 1930))
            {
                $iserror = true;
                $manager->addErorrMessageForField("bdate", "Ну чушь то не надо вводить а? Не дураки же тоже тут"); 
            }
            else
            {
                $scope['bdate'] = date("o-m-d", mktime(0, 0, 0, $data['bdate_day'], $data['bdate_mounth'], $data['bdate_year']));
            }
        }
        else
        {
            unset($data['bdate_day']);
            unset($data['bdate_mounth']);
            unset($data['bdate_year']);
        }
            
        //COUNTRY
        if(!empty($data['country']))
        {
            $countries = Countries_Helper::getCountries();
            if(strlen($data['country'])>2 || !key_exists($data['country'], $countries))
            {
                $iserror = true;
                $manager->addErorrMessageForField("contry", "Не верный формат ввода страны");     
            }
        }
        
        //CITY
        if (!empty($data['city'])) {
            if (strlen($data['city']) < 3) {
                $iserror = true;
                $manager->addErorrMessageForField("city", "Слишком короткое название города");
            } elseif (strlen($data['city']) > 64) {
                $iserror = true;
                $manager->addErorrMessageForField("city", "Слишком длинное название города");
            } elseif (!preg_match("/^[a-zа-я0-9]{3,64}+$/ui", $data['city'])) {
                $iserror = true;
                $manager->addErorrMessageForField("city", "Введены не допустимые символы");
            }
        }
        //SEX
        if (!empty($data['sex'])) {
            if (!is_numeric($data['sex'])) {
                $iserror = true;
                $manager->addErorrMessageForField("sex", "Указан не допустимый признак пола");
            } elseif (!in_array($data['sex'], array(0, 1))) {
                $iserror = true;
                $manager->addErorrMessageForField("sex", "Указан не допустимый признак пола");
            }
        }
        //WMID
        if (!empty($data['wmid'])) {
            if (!preg_match("/^[0-9]{12}$/ui", $data['wmid'])) {
                $iserror = true;
                $manager->addErorrMessageForField("wmid", "Не верный формат WMID");
            }
        }
        //WM POUCH
        if (!empty($data['wm_pouch'])) {
            if (!preg_match("/^[ZER][0-9]{12}$/ui", $data['wm_pouch'])) {
                $iserror = true;
                $manager->addErorrMessageForField("wm_pouch", "Не верный формат кошелька");
            }
        }  
        //GET NOTIFIES
        if (!empty($data['get_notifies'])) {
            if (!is_numeric($data['get_notifies'])) {
                $iserror = true;
                $manager->addErorrMessageForField("get_notifies", "Значение вне диапазона допустимых");
            } elseif (!in_array($data["get_notifies"], array(0, 1))) {
                $iserror = true;
                $manager->addErorrMessageForField("get_notifies", "Значение вне диапазона допустимых");
            }
        }
        //GET NEWTASKS
        if (!empty($data['get_newtasks'])) {
            if (!is_numeric($data['get_newtasks'])) {
                $iserror = true;
                $manager->addErorrMessageForField("get_newtasks", "Значение вне диапазона допустимых");
            } elseif (!in_array($data["get_newtasks"], array(0, 1))) {
                $iserror = true;
                $manager->addErorrMessageForField("get_newtasks", "Значение вне диапазона допустимых");
            }
        }
        
        if($iserror){  return VALIDATION_FAILED; }
        return VALIDATION_ACCEPTED;
    }
    public function submit_post_editprofile($data, $scope, $manager) {
        $need_to_update = array('user_nickname', 'user_email', 'country', 'city', 'sex', 'wmid', 'wm_pouch', 'get_notifies', 'get_newtasks');
       
        $params = array();
        foreach ($need_to_update as $value) {
            if (isset($data[$value]) && $data[$value] != $this->user->{$value}) {
                $params[$value] = $data[$value];
            }
        }
     
        if (isset($scope['bdate']) && $scope['bdate']!=$this->user->bdate)
            $params['bdate'] = $scope['bdate'];

           //$this->dump($params);
        if (!empty($params)) {
            if ($this->user->model->updateProfile($params, $this->user->user_id)) {
                Event::fireEvent("message", array('message' => 'Профиль обновлен'));
            }
            else
            {
                Event::fireEvent("message", array('message' => 'Ошибка обновления'));
            }
        }
        else
        {
            Event::fireEvent("message", array('message' => 'Нет данных для обновления'));
        }
    }
    public function validate_post_attachemail(&$data, &$scope, &$manager) {
        $is_error = false;
        if (empty($data['email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("email", "Укажите e-mail");
        } elseif (!preg_match("/^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$/ui", $data['email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("email", "Не допустимый формат e-mail");
        }
        return ($is_error?VALIDATION_FAILED:VALIDATION_ACCEPTED);
    }
    public function submit_post_attachemail($data, $scope, $manager) {   
        //setSessionVariable('vk_email',$data['email']);
        $this->email = $data['email'];
    }
    public function validate_post_registration(&$data, &$scope, &$manager) {
        $is_error = false;
        //EMAIL
        if (empty($data['user_email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("user_email", "Укажите e-mail");
        } elseif (!preg_match("/^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$/ui", $data['user_email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("email", "Не допустимый формат e-mail");
        } elseif ($this->user->model->hasUserInBaseByEmail($data['user_email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("user_email", "Такой e-mail уже используется в системе");
        } 
        //NICKNAME
        if (empty($data['user_nickname'])) {
            $is_error = true;
            $manager->addErorrMessageForField("user_nickname", "Укажите никнейм");
        } elseif (strlen($data['user_nickname']) < 3) {
            $is_error = true;
            $manager->addErorrMessageForField("user_nickname", "Слишком короткий никнейм");
        } elseif (strlen($data['user_nickname']) > 64) {
            $is_error = true;
            $manager->addErorrMessageForField("user_nickname", "Слишком длинный никнейм");
        } elseif (!preg_match("/^[a-zа-я0-9]{3,64}+$/ui", $data['user_nickname'])) {
            $is_error = true;
            $manager->addErorrMessageForField("user_nickname", "Введены недопустимые символы");
        } elseif ($this->user->model->hasUserInBaseByNickname($data['user_nickname'])) {
            $is_error = true;
            $manager->addErorrMessageForField("user_nickname", "Такой нинейм уже используется в системе");
        }
        
        //PASSWORD
        if(empty($data['user_password']))
        {
            $is_error = true;
            $manager->addErorrMessageForField("user_password", "Введите пароль");
        }
        elseif(strlen($data['user_password'])<6)
        {
            $is_error = true;
            $manager->addErorrMessageForField("user_password", "Минимальная длина пароля 6 символов");      
        }
        elseif(strlen($data['user_password'])>16)
        {
            $is_error = true;
            $manager->addErorrMessageForField("user_password", "Максимальная длина пароля 16 символов");      
        }
        elseif (!preg_match("/^[a-z0-9_-]{6,18}$/ui", $data['user_password'])) {
            $is_error = true;
            $manager->addErorrMessageForField("user_password", "В пароле указаны недопустимые символы");
        }
        elseif(empty($data['user_password_repeat']))
        {
            $is_error = true;
            $manager->addErorrMessageForField("user_password_repeat", "Повторите ввод пароля");  
        }
        elseif ($data['user_password'] != $data['user_password_repeat']) {
            $is_error = true;
            $manager->addErorrMessageForField("user_password_repeat", "Пароли не совпадают"); 
        }
        return ($is_error?VALIDATION_FAILED:VALIDATION_ACCEPTED);
    }
    public function submit_post_registration($data, $scope, $manager) {
        $user = $this->user;
        if($user->doRegistration($data))
        {
            Event::fireEvent("message", array('message' => 'Регистрация прошла успешно'));
        }
        else
        {
            Event::fireEvent("message", array('message' => 'Ошибка регистрации'));
        }
        //redirect(DIR_BASE);
        return $this->router->getAction('');
    }
    public function validate_post_sn_register_form(&$data, &$scope, &$manager) {   
        $is_error = false;
        
        //$manager->saveDataInToSession($data, 'sn_register_form');
        //EMAIL
        if (empty($data['email'])) {
            $is_error = true;
        } elseif (!preg_match("/^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$/ui", $data['email'])) {
            $is_error = true;
        }
        elseif ($this->user->model->hasUserInBaseByEmail($data['email'])) {
            $is_error = true;
            //$manager->addErorrMessageForField("user_email", "Такой e-mail уже используется в системе");
        }   
        else
            $this->email = $data['email'];

        //NICKNAME
        if (empty($data['nickname'])) {
            $is_error = true;
            $manager->addErorrMessageForField("nickname", "Укажите никнейм");
        } elseif (strlen($data['nickname']) < 3) {
            $is_error = true;
            $manager->addErorrMessageForField("nickname", "Слишком короткий никнейм");
        } elseif (strlen($data['nickname']) > 64) {
            $is_error = true;
            $manager->addErorrMessageForField("nickname", "Слишком длинный никнейм");
        } elseif (!preg_match("/^[a-zа-я0-9]{3,64}+$/ui", $data['nickname'])) {
            $is_error = true;
            $manager->addErorrMessageForField("nickname", "Введены недопустимые символы");
        } elseif ($this->user->model->hasUserInBaseByNickname($data['nickname'])) {
            $is_error = true;
            $manager->addErorrMessageForField("nickname", "Такой нинейм уже используется в системе");
        }
        
        //PASSWORD
        if(empty($data['password']))
        {
            $is_error = true;
            $manager->addErorrMessageForField("password", "Введите пароль");
        }
        elseif(strlen($data['password'])<6)
        {
            $is_error = true;
            $manager->addErorrMessageForField("password", "Минимальная длина пароля 6 символов");      
        }
        elseif(strlen($data['password'])>16)
        {
            $is_error = true;
            $manager->addErorrMessageForField("password", "Максимальная длина пароля 16 символов");      
        }
        elseif (!preg_match("/^[a-z0-9_-]{6,18}$/ui", $data['password'])) {
            $is_error = true;
            $manager->addErorrMessageForField("password", "В пароле указаны недопустимые символы");
        }
        elseif(empty($data['password_repeat']))
        {
            $is_error = true;
            $manager->addErorrMessageForField("password_repeat", "Повторите ввод пароля");  
        }
        elseif ($data['password'] != $data['password_repeat']) {
            $is_error = true;
            $manager->addErorrMessageForField("password_repeat", "Пароли не совпадают"); 
        }
        
        if($is_error)
        {
            Event::fireEvent('message', array('message'=>'Возникли ошибки при проверке формы'));
        }
        return ($is_error?VALIDATION_FAILED:VALIDATION_ACCEPTED);
    }
    public function submit_post_sn_register_form($data, $scope, $manager) {   
        $this->reg_data = $data;
    }
    public function validate_post_attachpassword(&$data, &$scope, &$manager) {       
        $is_error = false;
        
        if (empty($data['email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("email", "Укажите e-mail");
        } elseif (!preg_match("/^([a-z0-9_\.-]+)@([a-z0-9_\.-]+)\.([a-z\.]{2,6})$/ui", $data['email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("email", "Не допустимый формат e-mail");
        }
        elseif (!$this->user->model->hasUserInBaseByEmail($data['email'])) {
            $is_error = true;
            $manager->addErorrMessageForField("email", "Такой e-mail не используется в системе");
        }   
        elseif($user_data = $this->user->model->getUserDataByEmail($data['email']))
        {
            $this->email = $data['email'];
            if($user_data['user_password'] !=  md5(md5(trim($data['password']))))
            {
                $is_error = true;
                $manager->addErorrMessageForField("password", "Не верный пароль");
            }
        }
        
        if($is_error)
        {
            Event::fireEvent('message', array('message'=>'Возникли ошибки при проверке формы'));
        }
        
        return ($is_error?VALIDATION_FAILED:VALIDATION_ACCEPTED);
    }
    public function submit_post_attachpassword($data, $scope, $manager) {  
        $this->password = $data['password'];
    }
    //----HOOKS----//
    /**
     * хук вызываемый до всех вызовов методов обработки отображения страницы
     * сюда мы и запихнем авторизацию юзера
     * @param type $data
     */
    public static function hook_beforeinit(&$data) {
        
       $reg = Registry::getInstance();
       $reg->load->library('class.User.php', 'user');
       $reg->load->library('class.CurrentUser.php', 'user');
       
        $user = new CurrentUser();
        $reg->set('user', $user);
    }
}
?>
